package org.example.utils;

/**
 * @author 胡帅博
 * @date 2021/6/11 15:58
 */

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileRead{


    //相对路径
    public static byte[] readFromJar(String path) throws IOException {

        ByteArrayOutputStream bos = null;
        BufferedInputStream in = null;
        try {
            InputStream resourceAsStream = FileRead.class.getResourceAsStream(path);
            bos = new ByteArrayOutputStream(((int) resourceAsStream.available()));
            in = new BufferedInputStream(resourceAsStream);
            int bufSize = 1024;
            byte[] buffer = new byte[bufSize];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, bufSize))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }


    //相对路径
    public static InputStream getFileInputStream(String path) throws IOException {
        try {
            InputStream resourceAsStream = FileRead.class.getResourceAsStream(path);
            return resourceAsStream;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
